package com.src.xyzk_personal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.src.xyzk_personal.R;
import com.src.xyzk_personal.EOL.DbAdapter;
import com.src.xyzk_personal.config.Common;
import com.src.xyzk_personal.config.Commonfunc;
import com.src.xyzk_personal.config.EcuModule;
import com.src.xyzk_personal.config.Message;
import com.src.xyzk_personal.config.ServerSocket;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class SystemSettingActivity extends Activity{
	private static String TAG = "SystemSettingActivity";
	Context context = SystemSettingActivity.this;

	private EditText m_vin = null;	//ip地址
	private TextView m_startdate = null;
	private TextView m_starttime = null;
	private TextView m_enddate = null;
	private TextView m_endtime = null;
	private Button m_search = null;
	//start date
	int [] m_start_time = new int[6];
	int [] m_end_time = new int[6];
	//ListView列表
	private ListView m_listdata = null;
	private ArrayList<Map<String, String>> m_listdataArray = null;
	private ListSearchAdapter m_listdata_adapter = null;

	//对话框
	private ProgressDialog progressdialog;
	//缓存
	SharedPreferences.Editor m_editor = null;
	SharedPreferences m_pref = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.system_setting_activity);

		InitView();
		///--------------------test----------------
		//m_vin.setText("LUZBGAFB9NA007793");
	}

	void InitView()
	{
		//edit
		m_vin = (EditText)findViewById(R.id.system_edit_vin);
		//button
		m_search = (Button) findViewById(R.id.system_search);
		//start
		m_startdate = (TextView) findViewById(R.id.system_get_start_date);
		m_starttime = (TextView) findViewById(R.id.system_get_start_time);
		m_enddate = (TextView) findViewById(R.id.system_get_end_date);
		m_endtime = (TextView) findViewById(R.id.system_get_end_time);
		//初始化
		for(int k = 0; k < 6; k ++)
		{
			m_start_time[k] = 0;
			m_end_time[k] = 0;
		}
		m_startdate.setText(m_start_time[0] + "年" + m_start_time[1] + "月" + m_start_time[2] + "日");
		m_enddate.setText(m_end_time[0] + "年" + m_end_time[1] + "月" + m_end_time[2] + "日");
		m_endtime.setText(m_end_time[3] + ":" + m_end_time[4] + ":" + m_end_time[5] + "");
		m_endtime.setText(m_end_time[3] + ":" + m_end_time[4] + ":" + m_end_time[5] + "");
		//列表初始化
		m_listdata = (ListView)findViewById(R.id.system_show_list);
		m_listdataArray = new ArrayList<Map<String,String>>();
		m_listdata_adapter = new ListSearchAdapter(m_listdataArray);
		m_listdata.setAdapter(m_listdata_adapter);
		m_listdata.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				m_listdata_adapter.setSelected(position);
				m_listdata_adapter.notifyDataSetChanged();
				//上传数据
				m_search.setEnabled(false);

				UpdateDataToServer(position);

				m_search.setEnabled(true);
			}
		});
	}
	void UpdateDataToServer(int Pselect)
	{
		final int v_select = Pselect;
		progressdialog = ProgressDialog.createDialog(context,"上传数据...");
		new Thread(new Runnable() {

			@Override
			public void run()
			{
				// TODO Auto-generated method stub
				boolean isok = ThreadUpdataToServer(v_select);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				m_syshandler.obtainMessage(Message.MSG_Dialog_close, 1, 0).sendToTarget();

			}
		}).start();

		return;
	}
	boolean ThreadUpdataToServer(int Pselect)
	{
		//组装数据
		String v_vin = m_listdataArray.get(Pselect).get("VIN");
		String v_station = m_listdataArray.get(Pselect).get("STATION");
		String v_testnum = m_listdataArray.get(Pselect).get("TESTNUM");
		//查询数据
		ArrayList<Map<String, String>> m_listdetail = null;
		DbAdapter db = new DbAdapter(context);
		db.open();
		m_listdetail = (ArrayList<Map<String, String>>) db.queryDataTable(v_vin, "m_testnum=?", new String[]{v_testnum}, null, null);
		db.close();
		String v_up = "6:[" + v_vin + ", " + v_station + "]end,";
		v_up += m_listdetail.toString();

		return UpdataToDb(v_up);
	}
	private boolean UpdataToDb(String Upstr)
	{
		boolean isok = false;
		ServerSocket v_server = new ServerSocket();
		for(int i = 0; i < 3; i ++)
		{
			if(v_server.ConnectServer(Common.Server_IP, Common.Server_PORT))
			{
				isok = v_server.SendDataToServer(Commonfunc.IntToHeadStr(Upstr.getBytes().length) + Upstr);

				v_server.close();
				break;
			}
		}
		return true;
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	public void SetStartDate(View v) {

		new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
								  int dayOfMonth) {
				m_start_time[0] = year;
				m_start_time[1] = monthOfYear + 1;
				m_start_time[2]= dayOfMonth;
				m_startdate.setText(m_start_time[0] + "年" + m_start_time[1] + "月" + m_start_time[2] + "日");
			}
		}, 2022, 02, 19).show();

	}
	public void SetEndDate(View v) {

		new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
								  int dayOfMonth) {
				m_end_time[0] = year;
				m_end_time[1] = monthOfYear + 1;
				m_end_time[2]= dayOfMonth;
				m_enddate.setText(m_end_time[0] + "年" + m_end_time[1] + "月" + m_end_time[2] + "日");
			}
		}, 2022, 02, 19).show();

	}
	public void SetStartTime(View v) {
		new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				m_start_time[3] = hourOfDay;
				m_start_time[4] = minute;
				m_start_time[5] = 0;
				m_starttime.setText(m_start_time[3] + ":" + m_start_time[4] + ":" + m_start_time[5] + "");
			}
		}, 00, 00, true).show();

	}
	public void SetEndTime(View v) {
		new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				m_end_time[3] = hourOfDay;
				m_end_time[4] = minute;
				m_end_time[5] = 0;
				m_endtime.setText(m_end_time[3] + ":" + m_end_time[4] + ":" + m_end_time[5] + "");
			}
		}, 00, 00, true).show();

	}
	//查询数据
	public void SearchData(View v) {
		//先检测条件
		if(m_vin.getText().toString().length() == 17) //有VIN
		{

		}
		else  //按时间,判断时间
		{
			if(m_start_time[0] == 0 || m_end_time[0] == 0) //未设置
			{
				Toast.makeText(context, "请设置起止时间！", Toast.LENGTH_LONG).show();
				return;
			}
		}
		m_listdataArray.clear();

		DbAdapter db = new DbAdapter(context);
		db.open();
		ArrayList<Map<String,String>> list = db.UpquerymainTable("m_vin=? and m_carname=? and m_result='OK'", new String[]{m_vin.getText().toString(),"整车出厂检测"}, null, null);
		if(list != null)
		{
			for(int k = 0; k < list.size(); k ++)
				m_listdataArray.add(list.get(k));
		}
		m_syshandler.obtainMessage(Message.MSG_IndivateList).sendToTarget();
		db.close();

	}

	//插入数据
	private void AddDataToList(int id,String Pvin,String Pstation,String Pcar,String Pcolor,String Ptime,String Ptestnum,String Presult,String Pup,String Puser)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("ID", id + "");
		map.put("VIN", Pvin);
		map.put("STATION", Pstation);
		map.put("CAR", Pcar);
		map.put("COLOR", Pcolor);
		map.put("TIME", Ptime);
		map.put("TESTNUM", Ptestnum);
		map.put("RESULT", Presult);
		map.put("UP", Pup);
		map.put("USER", Puser);
		m_syshandler.obtainMessage(Message.MSG_ShowArray, map).sendToTarget();
	}
	//class
	public class ListSearchAdapter extends BaseAdapter
	{
		private ArrayList<Map<String, String>> listdata = null;
		private SystemListShow listshow = null;
		private View view = null;
		private LayoutInflater inflater = null;
		private int Selected = -1;
		public ListSearchAdapter(ArrayList<Map<String, String>> Pdata) {
			// TODO Auto-generated constructor stub
			listdata = Pdata;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if(listdata != null)
				return listdata.size();
			else
				return 0;
		}
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			if(listdata != null && listdata.size() > position)
				return listdata.get(position);
			else
				return null;
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		public void setSelected(int pos)
		{
			Selected = pos;
		}
		public int getSelected()
		{
			return Selected;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = inflater.inflate(R.layout.system_search_listview, null, false);
			listshow = (SystemListShow) view.getTag();
			if(listshow == null)
			{
				listshow = new SystemListShow();
				listshow.id = (TextView)view.findViewById(R.id.system_search_list_id);
				listshow.vin = (TextView)view.findViewById(R.id.system_search_list_vin);
				listshow.station = (TextView)view.findViewById(R.id.system_search_list_station);
				listshow.car = (TextView)view.findViewById(R.id.system_search_list_car);
				listshow.color = (TextView)view.findViewById(R.id.system_search_list_color);
				listshow.time = (TextView)view.findViewById(R.id.system_search_list_time);
				listshow.testnum = (TextView)view.findViewById(R.id.system_search_list_testnum);
				listshow.result = (TextView)view.findViewById(R.id.system_search_list_result);
				listshow.up = (TextView)view.findViewById(R.id.system_search_list_up);
				listshow.user = (TextView)view.findViewById(R.id.system_search_list_user);
				view.setTag(listshow);
			}
			if(listdata.get(position).get("RESULT").equals("2"))
			{
				view.setBackgroundColor(Color.RED);
			}
			else if(position == Selected)
			{
				//listlayout.text.setBackgroundColor(Color.GREEN);
				view.setBackgroundColor(Color.GREEN);
				listshow.id.setSelected(true);
				listshow.id.setPressed(true);
			}
			else if(position % 2 == 1)
			{
				listshow.id.setSelected(false);
				listshow.id.setPressed(false);
				view.setBackgroundColor(0xFFC0C0C0);
			}
			else
			{
				listshow.id.setSelected(false);
				listshow.id.setPressed(false);
				view.setBackgroundColor(Color.WHITE);
			}
			listshow.id.setText(listdata.get(position).get("ID"));
			listshow.vin.setText(listdata.get(position).get("VIN"));
			listshow.station.setText(listdata.get(position).get("STATION"));
			listshow.car.setText(listdata.get(position).get("CAR"));
			listshow.color.setText(listdata.get(position).get("COLOR"));
			listshow.time.setText(listdata.get(position).get("TIME"));
			listshow.testnum.setText(listdata.get(position).get("TESTNUM"));
			listshow.result.setText(listdata.get(position).get("RESULT"));
			listshow.up.setText(listdata.get(position).get("UP"));
			listshow.user.setText(listdata.get(position).get("USER"));
			return view;
		}
	}
	class SystemListShow
	{
		TextView id;
		TextView vin;
		TextView station;
		TextView car;
		TextView color;
		TextView time;
		TextView testnum;
		TextView result;
		TextView up;
		TextView user;
	}

	private final Handler m_syshandler = new Handler()
	{
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case Message.MSG_ShowArray:
					m_listdataArray.add((HashMap<String, String>)msg.obj);
					m_listdata_adapter.notifyDataSetChanged();
					break;
				case Message.MSG_IndivateList:
					m_listdata_adapter.notifyDataSetChanged();
					break;
				case Message.MSG_Dialog_close:
					progressdialog.dismiss();
					if(msg.arg1 == 1) //ok
					{
						Toast.makeText(context, "上传成功!", Toast.LENGTH_LONG).show();
					}
					else
					{
						Toast.makeText(context, "上传失败!", Toast.LENGTH_LONG).show();
					}
					break;
				default:
					break;
			}
		};
	};

}
